//
//  CloneCommon.swift
//  JKConsole
//
//  Created by 姜奎 on 2020/6/17.
//  Copyright © 2020 JK. All rights reserved.
//

import Foundation
class CloneCommon: CommonProtocol {
   
    func run(options: ConsoleOptions) {
        let project: Project
        if let path = options.path {
            project = Project(directoryPath: path)
        }else {
            project = Project()
        }
        guard project.rootPath == project.directoryPath else {
            print(Colors.red("请在项目根目录执行脚本"))
            exit(EXIT_FAILURE)
        }
        print(Colors.green("======开始准备clone子模块======"))
        do {
            try shellOut(to: .removeFolder(from: project.rootModulePath))
        } catch {
            print(Colors.yellow("Clone 命令执行异常！删除工程Module文件夹失败"))
        }
        
        let list = self.clone(pro: project, checkoutsPath: project.checkoutsPath, fileManager: project.fileManager)
        var recordList:[String] = []
        for item in list.reversed() {
            if !recordList.contains(item) {
                recordList.append(item)
            }
        }
        print(Colors.green("Clone 命令执行结束！"))
        do {
            let data = try JSONSerialization.data(withJSONObject: recordList, options: .fragmentsAllowed)
            try data.write(to: URL(fileURLWithPath: project.recordListPath), options: .atomicWrite)
            print(Colors.green("Modulefile.recordList 写入成功"))
        } catch {
            print(Colors.yellow("Modulefile.recordList 写入失败"))
        }
        print(Colors.green("======clone子模块结束======"))
    }
    
    func clone(pro: Project,checkoutsPath: String, fileManager: FileManager) -> [String] {
        var recordList:[String] = []
        for module in pro.moduleList {
            do {
                try shellOut(to: .gitClone(url: module.url, to: pro.rootCheckoutsPath + "/" + module.name))
                print(Colors.green("\(module.name):clone成功"))
            } catch {
                print(Colors.yellow("\(module.name) 已经存在,无需Clone！"))
            }
            let pro1 = Project(directoryPath: "\(checkoutsPath)/\(module.name)")
            let list = self.clone(pro: pro1,checkoutsPath:checkoutsPath, fileManager: fileManager)
            recordList.append(module.name)
            recordList += list
            
        }
        
        return recordList
    }
    
    
}
